package handler

import (
	"gitee.com/DonHz/simple-blog-system/handler/middleware"
	"gitee.com/DonHz/simple-blog-system/model"
	"gitee.com/DonHz/simple-blog-system/util/logger"
	"github.com/gin-gonic/gin"
	"net/http"
	"strconv"
	"time"
)

func (h *ArticleHandler) BlogList(ctx *gin.Context) {
	uid, err := strconv.Atoi(ctx.Param("uid"))
	if err != nil {
		ReturnError(ctx, 5, "系统异常")
		return
	}
	arts, err := h.dao.GetArticleByUserId(ctx, int64(uid))
	logger.LogRus.Debugf("get %d blogs of userId %d", len(arts), uid)
	ctx.HTML(http.StatusOK, "blog_list.html", arts)
}

func (h *ArticleHandler) BlogDetail(ctx *gin.Context) {
	articleId := ctx.Param("aid")
	aid, err := strconv.Atoi(articleId)
	if err != nil {
		ReturnError(ctx, 5, "系统异常")
		return
	}
	article, err:=h.dao.GetArticleById(ctx, int64(aid))
	if err!=nil{
		ReturnError(ctx, 4, "文章不存在")
	}
	ctx.HTML(http.StatusOK, "blog.html", gin.H{
		"id":article.Id,
		"title": article.Title,
		"content": article.Content,
		"author_id": article.AuthorId,
		"update_time": time.UnixMilli(article.UpdateTime).Format("2006-01-02 15:04:05"),
	})
}

func (h *ArticleHandler) BlogUpdate(ctx *gin.Context) {
	type UpdateRequest struct {
		Id int64 `form:"aid" binding:"gt=0"`
		Title string `form:"title" binding:"gt=0"`
		Content string `form:"content" binding:"gt=0"`
	}
	var req UpdateRequest
	err:=ctx.ShouldBind(&req)
	if err!=nil{
		ReturnError(ctx, 5, "参数异常")
		return
	}
	aid:=req.Id
	article, err:=h.dao.GetArticleById(ctx, int64(aid))
	if err!=nil{
		ReturnError(ctx, 4, "文章不存在")
		return
	}
	loginUid:=ctx.Value("uid")
	if loginUid.(int64) != article.AuthorId {
		ctx.String(http.StatusForbidden, "非法操作")
		return
	}
	err=h.dao.UpdateArticle(ctx, model.Article{
		Id: int64(aid),
		Title: req.Title,
		Content: req.Content,
	})
	if err!=nil{
		logger.LogRus.Errorf("update article %d failed: %v", aid, err)
		ReturnError(ctx, 5, "系统异常")
		return
	}
	ReturnSuccess(ctx, 200, "更新成功", aid, 1)
}

func (h *ArticleHandler) BlogBelong(ctx *gin.Context) {
	token:=ctx.Query("token")
	aids, err:=strconv.Atoi(ctx.Query("aid"))
	aid:=int64(aids)
	if err!=nil{
		logger.LogRus.Error("无效的blog id")
		ReturnError(ctx, 5, "系统异常")
		return
	}
	article, err:=h.dao.GetArticleById(ctx, aid)
	if err!=nil{
		logger.LogRus.Error("blog 不存在")
		ReturnError(ctx, 5, "系统异常")
		return
	}
	loginUid:=middleware.GetUidFromJWT(token)
	if loginUid!=article.AuthorId {
		ctx.JSON(http.StatusOK, "false")
	}
	ctx.JSON(http.StatusOK, "true")
}